import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Toast } from 'vant'

const instance = axios.create({
  baseURL: 'https://api.shop.eduwork.cn',
  timeout: 5000
})

// 请求拦截
instance.interceptors.request.use(config => {
  // 登录之后的请求携带token
  const token = window.localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  // 设置用户token
  return config // 放心
})
// 响应拦截
instance.interceptors.response.use(res => res, rej => {
  // 若是去往需要认证的页面
  if (rej.response?.status === 401 && store.state.user.isLogin === false) {
    Toast.fail('请先登录')
    router.push('/login')
  }
  return rej.response
})

export default (url, method, requestData) => {
  return instance({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: requestData
  })
}
